import time, os, sys, network
import socket
import _thread
import gc
import utime  # 添加utime模块导入

from media.sensor import *
from media.display import *
from media.media import *
from CameraStreamer import CameraStreamer

def setup_ap_mode():
    """设置AP模式"""
    print("[调试] 初始化AP模式...")
    ap = network.WLAN(network.AP_IF)
    ap.active(True)
    ap.config(ssid="K230-Camera", key="12345678")
    print("[调试] AP模式已启动，IP:", ap.ifconfig()[0])
    return ap

def http_server():
    """HTTP服务器线程"""
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.bind(('0.0.0.0', 80))
        s.listen(5)
        print("[调试] HTTP服务器已启动，监听端口80")
        
        while True:
            conn, addr = s.accept()
            print("[调试] 新HTTP客户端连接:", addr)
            
            # 读取请求
            request = conn.recv(1024).decode('utf-8')
            
            # 发送响应
            response = """HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8

<!DOCTYPE html>
<html>
<head>
    <title>K230 Camera</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
    <h1>K230 Camera Web Server</h1>
    <p>请使用WebSocket客户端连接到 ws://192.168.169.1:6001 查看视频流</p>
    <p>或直接打开 <a href="/direct_client.html">直接客户端</a></p>
</body>
</html>
"""
            conn.send(response.encode('utf-8'))
            conn.close()
    except Exception as e:
        print("[调试] HTTP服务器错误:", e)

def main_camera_stream():
    print("[调试] 导入垃圾回收器...")
    import gc
    
    print("[调试] 执行初始垃圾回收...")
    gc.collect()
    
    print("[调试] 检查可用内存...")
    try:
        free_mem = gc.mem_free()
        total_mem = gc.mem_alloc() + free_mem
        print(f"[调试] 可用内存: {free_mem} 字节 / 总内存: {total_mem} 字节 ({free_mem*100/total_mem:.1f}%)")
        
        if free_mem < 500000:  # 如果可用内存小于500KB
            print("[警告] 可用内存较低，尝试释放更多内存...")
            # 强制执行多次垃圾回收
            for i in range(3):
                gc.collect()
                time.sleep_ms(100)
            
            # 再次检查内存
            free_mem = gc.mem_free()
            total_mem = gc.mem_alloc() + free_mem
            print(f"[调试] 垃圾回收后可用内存: {free_mem} 字节 / 总内存: {total_mem} 字节 ({free_mem*100/total_mem:.1f}%)")
    except Exception as e:
        print("[错误] 内存检查失败:", e)
    
    try:
        # 设置AP模式
        ap = setup_ap_mode()
        if not ap:
            print("[错误] 无法设置AP模式，程序退出")
            return
        
        # 启动HTTP服务器线程
        print("[调试] 启动HTTP服务器线程...")
        try:
            _thread.start_new_thread(http_server, ())
            print("[调试] HTTP服务器线程已启动")
        except Exception as e:
            print("[错误] 启动HTTP服务器线程失败:", e)
        
        # 配置媒体管理器
        print("[调试] 配置媒体管理器...")
        try:
            config = k_vb_config()
            config.max_pool_cnt = 1
            config.comm_pool[0].blk_size = 1024
            config.comm_pool[0].blk_cnt = 1
            config.comm_pool[0].mode = VB_REMAP_MODE_NOCACHE
            ret = MediaManager._config(config)
            if not ret:
                raise RuntimeError("缓冲区配置失败")
            print("[调试] 媒体管理器配置成功")
        except Exception as e:
            print("[错误] 媒体管理器配置失败:", e)
            return
            
        # 初始化传感器
        print("[调试] 初始化传感器...")
        try:
            sensor = Sensor(id=2)
            sensor.reset()
            
            # 设置通道0用于显示
            print("[调试] 设置传感器通道0用于显示...")
            sensor.set_framesize(width=640, height=480, chn=CAM_CHN_ID_0)
            sensor.set_pixformat(Sensor.RGB565, chn=CAM_CHN_ID_0)
            
            # 设置通道2用于编码
            print("[调试] 设置传感器通道2用于编码...")
            sensor.set_framesize(width=640, height=360, chn=CAM_CHN_ID_2)
            sensor.set_pixformat(Sensor.YUV420SP, chn=CAM_CHN_ID_2)
            
            print("[调试] 传感器参数设置完成")
        except Exception as e:
            print("[错误] 传感器初始化失败:", e)
            return
        
        # 创建CameraStreamer实例
        print("[调试] 创建CameraStreamer实例...")
        try:
            streamer = CameraStreamer(
                ip="0.0.0.0",          # 监听所有接口
                port=6001,             # WebSocket服务器端口
                w=640,                 # 视频宽度
                h=360,                 # 视频高度
                sensor=sensor,         # 传感器实例
                mode="websocket"       # 使用WebSocket模式
            )
            print("[调试] CameraStreamer实例创建成功")
        except Exception as e:
            print("[错误] 创建CameraStreamer实例失败:", e)
            return
        
        # 初始化媒体管理器 - 确保在sensor.run()前调用
        print("[调试] 初始化媒体管理器...")
        try:
            MediaManager.init()
            print("[调试] 媒体管理器初始化成功")
        except Exception as e:
            print("[错误] 媒体管理器初始化失败:", e)
            return
            
        # 启动传感器 - 不传递参数
        print("[调试] 启动传感器...")
        try:
            sensor.run()  # 不传递参数
            print("[调试] 传感器启动成功")
            # 等待传感器稳定
            time.sleep(1)
        except Exception as e:
            print("[错误] 传感器启动失败:", e)
            MediaManager.deinit()
            return
            
        # 启动CameraStreamer
        print("[调试] 启动CameraStreamer...")
        try:
            streamer.start()
            print("[调试] CameraStreamer启动成功")
        except Exception as e:
            print("[错误] 启动CameraStreamer失败:", e)
            streamer.deinit()
            sensor.stop()
            MediaManager.deinit()
            return
            
            # 主循环
    print("[调试] 进入主循环...")
    clock = utime.clock()  # 改为使用utime.clock()
    while True:
        try:  # 添加错误处理
            clock.tick()
            
            # 检查是否有客户端连接
            streamer.check()
            
            # 获取图像并显示
            img = sensor.snapshot(chn=CAM_CHN_ID_0)  # 使用通道0的图像显示
            
            # 在图像上绘制信息
            img.draw_string_advanced(10, 10, 24, f"FPS: {clock.fps():.1f}", color=(255, 0, 0))
            img.draw_string_advanced(10, 40, 24, f"IP: {ap.ifconfig()[0]}", color=(255, 0, 0))
            img.draw_string_advanced(10, 70, 24, f"连接: {streamer.get_client_count() if hasattr(streamer, 'get_client_count') else '?'}", color=(255, 0, 0))
            
            # 允许其他任务执行
            utime.sleep_ms(10)  # 改为使用utime
            
            # 垃圾回收
            if clock.fps() < 10:
                print("[警告] 帧率低于10FPS，执行垃圾回收...")
                gc.collect()
            
            # 退出点
            os.exitpoint()
            
        except Exception as e:  # 捕获循环中可能的异常
            print(f"[错误] 主循环中出现异常: {e}")
            utime.sleep_ms(100)  # 给系统一些恢复的时间
            continue
            
    except KeyboardInterrupt:
        print("[调试] 用户中断")
    except Exception as e:
        print("[错误] 主循环异常:", e)
    finally:
        print("[调试] 清理资源...")
        try:
            if 'streamer' in locals():
                streamer.deinit()
        except Exception as e:
            print("[错误] 清理streamer失败:", e)
        try:
            if 'sensor' in locals():
                sensor.stop()
        except Exception as e:
            print("[错误] 停止sensor失败:", e)
        try:
            MediaManager.deinit()
        except Exception as e:
            print("[错误] 清理MediaManager失败:", e)
        print("[调试] 程序结束")

def test_ap_mode():
    """简单测试AP模式和基本功能，不包含复杂的视频流处理"""
    print("[测试] 开始简单AP模式测试...")
    
    # 设置AP模式
    ap = setup_ap_mode()
    if not ap:
        print("[测试] AP模式设置失败，测试结束")
        return
    
    print("[测试] AP模式设置成功，IP: " + ap.ifconfig()[0])
    
    # 启动简单的HTTP服务器
    try:
        print("[测试] 启动简单HTTP服务器...")
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.bind(('0.0.0.0', 80))
        s.listen(5)
        s.setblocking(False)
        print("[测试] HTTP服务器启动成功，监听端口80")
        
        # 启动简单的WebSocket服务器
        print("[测试] 启动简单WebSocket服务器...")
        ws = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        ws.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        ws.bind(('0.0.0.0', 6001))
        ws.listen(5)
        ws.setblocking(False)
        print("[测试] WebSocket服务器启动成功，监听端口6001")
        
        # 简单测试循环
        print("[测试] 开始测试循环，按Ctrl+C终止...")
        test_start_time = time.ticks_ms()
        while True:
            # 检查HTTP连接
            try:
                conn, addr = s.accept()
                print("[测试] 收到HTTP连接: " + str(addr))
                conn.send(b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\nK230 AP Mode Test Success!")
                conn.close()
            except:
                pass
                
            # 检查WebSocket连接
            try:
                conn, addr = ws.accept()
                print("[测试] 收到WebSocket连接: " + str(addr))
                # 发送简单响应
                conn.send(b"HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n")
                conn.close()
            except:
                pass
                
            # 每5秒打印一次状态
            if time.ticks_diff(time.ticks_ms(), test_start_time) > 5000:
                print("[测试] AP模式正常运行中，IP: " + ap.ifconfig()[0])
                test_start_time = time.ticks_ms()
                
            time.sleep_ms(100)
            os.exitpoint()
            
    except KeyboardInterrupt:
        print("[测试] 用户中断，测试结束")
    except Exception as e:
        print("[测试] 错误: " + str(e))
    finally:
        try:
            s.close()
        except:
            pass
        try:
            ws.close()
        except:
            pass
        print("[测试] 测试完成")

def test_camera():
    """简单测试摄像头功能，不包含网络部分"""
    print("[测试] 开始简单摄像头测试...")
    
    import gc
    gc.collect()
    
    try:
        # 初始化显示
        print("[测试] 初始化显示...")
        Display.init(Display.ST7701, width=800, height=480, osd_num=2, to_ide=True)
        print("[测试] 显示初始化成功")
        
        # 配置媒体管理器
        print("[测试] 配置媒体管理器...")
        from media.media import k_vb_config, VB_REMAP_MODE_NOCACHE
        config = k_vb_config()
        config.max_pool_cnt = 1
        config.comm_pool[0].blk_size = 1024
        config.comm_pool[0].blk_cnt = 1
        config.comm_pool[0].mode = VB_REMAP_MODE_NOCACHE
        MediaManager._config(config)
        print("[测试] 媒体管理器配置成功")
        
        # 初始化媒体管理器
        print("[测试] 初始化媒体管理器...")
        
        print("[测试] 媒体管理器初始化成功")
        
        # 初始化传感器
        print("[测试] 初始化传感器...")
        sensor = Sensor(id=2)
        sensor.reset()
        
        # 设置分辨率
        print("[测试] 设置传感器分辨率...")
        sensor.set_framesize(width=640, height=360, chn=CAM_CHN_ID_2)
        sensor.set_pixformat(Sensor.RGB888, chn=CAM_CHN_ID_2)
        
        print("[测试] 启动传感器...")
        MediaManager.init()
        sensor.run()
        print("[测试] 传感器启动成功")
        
        # 创建时钟
        print("[测试] 创建时钟...")
        clock = utime.clock()
        
        # 主循环
        print("[测试] 开始主循环，按Ctrl+C终止...")
        while True:
            clock.tick()
            
            # 获取图像
            img = sensor.snapshot(chn=CAM_CHN_ID_2)
            
            # 显示FPS
            img.draw_string_advanced(10, 10, 24, f"FPS: {clock.fps():.1f}", color=(255, 0, 0))
            
            # 显示图像
            Display.show_image(img)
            
            os.exitpoint()
            
    except KeyboardInterrupt:
        print("[测试] 用户中断，测试结束")
    except Exception as e:
        print("[测试] 错误: " + str(e))
    finally:
        try:
            sensor.stop()
        except:
            pass
        try:
            Display.deinit()
        except:
            pass
        try:
            MediaManager.deinit()
        except:
            pass
        print("[测试] 测试完成")

if __name__ == "__main__":
    # 如果需要仅测试AP模式和基本网络功能，取消下面一行的注释
    # test_ap_mode()
    
    # 如果需要仅测试摄像头功能，取消下面一行的注释
    # test_camera()
    
    # 正常启动完整功能
    main_camera_stream()
